package com.lnkwe.interceptor.admin;

import com.lnkwe.constant.SessionConstant;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger= Logger.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            String redirectUrl=request.getRequestURI();
            System.out.println("url:"+redirectUrl);
            HttpSession session=request.getSession();
            Object user = session.getAttribute(SessionConstant.SYSUSER);
            if(user==null){
                //如果用户没有登陆，则跳转登陆页面
                String msg= (String) request.getAttribute("msg");
                response.sendRedirect("/admin/user/login");
                return false;
            }
            else{
                session.setAttribute(SessionConstant.REDIRECTURL,"/");
                //response.sendRedirect("/");
                return true;
            }

        }catch(Exception e){
            e.printStackTrace();
            response.sendRedirect("/admin/user/login");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
